package com.qyer.search.utils;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * User: Z J Wu Date: 2016/01/21 Time: 15:06 Package: com.qyer.search.utils
 */
public class ESUtils {

  public static BulkResponse indexDataBulk(Client client, String indexName, String indexType,
                                           List<Map<String, Object>> bulk) {
    if (CollectionUtils.isEmpty(bulk)) {
      return null;
    }
    System.out.println("Do bulk, bulk size is " + bulk.size());
    BulkRequestBuilder bulkRequest = client.prepareBulk();
    for (Map<String, Object> sku : bulk) {
      System.out.println(sku.get("title"));
      bulkRequest.add(
        client.prepareIndex(indexName, indexType, String.valueOf(sku.get("lid"))).setSource(sku));
    }
    BulkResponse bulkResponse = bulkRequest.get();
    System.out.println("bulk done");
    return bulkResponse;
  }

  public static void insertFromFile(String fileName) throws IOException {
    Client client = null;
    String line;
    String[] lineArray;
    Map<String, Object> map;

    Map<Integer, String> countryMap = new HashMap<>(250);
    File countryFile = new File("/Users/WuZijing/securecrt_rzsz/country_with_name.tsv");
    try (BufferedReader br = new BufferedReader(
      new InputStreamReader(new FileInputStream(countryFile)))) {
      while ((line = br.readLine()) != null) {
        lineArray = StringUtils.split(line, '\t');
        countryMap.put(Integer.parseInt(lineArray[0]), lineArray[1]);
      }
    }

    Map<String, Object> innerMap;
    List<Map<String, Object>> innerMapList;
    String[] countryIdStr;
    Map<Integer, Map<String, Object>> productMap = new HashMap<>(5000);
    int lid;
    Random random = new Random();
    try (BufferedReader br = new BufferedReader(
      new InputStreamReader(new FileInputStream(fileName)))) {
      while ((line = br.readLine()) != null) {
        lineArray = StringUtils.split(line, '\t');
        lid = Integer.parseInt(lineArray[0]);
        map = productMap.get(lid);
        if (map == null) {
          map = new HashMap<>();
          map.put("lid", lid);
          map.put("title", lineArray[1]);
          map.put("cid", Integer.parseInt(lineArray[2]));
          map.put("ccid", Integer.parseInt(lineArray[3]));
          countryIdStr = StringUtils.split(lineArray[4], ',');
          innerMapList = new ArrayList<>(10);
          for (String idStr : countryIdStr) {
            innerMap = new HashMap<>(2);
            int countryId = Integer.parseInt(StringUtils.trimToNull(idStr));
            innerMap.put("id", countryId);
            innerMap.put("country", countryMap.get(countryId));
            innerMapList.add(innerMap);
          }
          map.put("countries", innerMapList);
          map.put("tags", new ArrayList<>());
          productMap.put(lid, map);
        }
        innerMapList = (List<Map<String, Object>>) map.get("tags");
        innerMap = new HashMap<>(5);
        innerMap.put("tid", Integer.parseInt(lineArray[5]));
        innerMap.put("tag_name", lineArray[6]);
        innerMap.put("tag_type", 1);
        innerMap.put("status", 0);
        innerMap
          .put("coefficient", Double.parseDouble(String.format("%.2f", random.nextDouble() * 10)));
        innerMapList.add(innerMap);
      }

      int cnt = 0, bulkSize = 20;
      List<Map<String, Object>> bulk = new ArrayList<>(bulkSize);
      for (Map<String, Object> skuMap : productMap.values()) {
        if (cnt >= bulkSize) {
          indexDataBulk(client, "products", "products", bulk);
          bulk = new ArrayList<>(bulkSize);
          cnt = 0;
        }
        ++cnt;
        bulk.add(skuMap);
      }
      indexDataBulk(client, "products", "products", bulk);
    }
  }
}
